package db

import (
	"context"
	"gorm.io/gorm"
	"jmicro/app/user/srv/internal/data/v1"
	"jmicro/app/user/srv/internal/domain/do"
	"jmicro/jmicro/code"
	metav1 "jmicro/pkg/common/meta/v1"
	"jmicro/pkg/errors"
)

type users struct {
	db *gorm.DB
}

func NewUsers(db *gorm.DB) v1.UserStore {
	return &users{db: db}
}
func (u *users) List(ctx context.Context, orderby []string, opts metav1.ListMeta) (*do.UserDOList, error) {
	//实现gorm查询
	ret := do.UserDOList{}
	//分页
	var limit, offset int
	if opts.PageSize == 0 {
		limit = 10
	} else {
		limit = opts.PageSize
	}
	if opts.Page > 0 {
		offset = (opts.Page - 1) * limit
	}
	//排序
	query := u.db
	for _, value := range orderby {
		//坑：如果db改掉了？
		//u.db=u.db.Order(value)
		query = query.Order(value)
	}
	//查询 - 发起多个请求
	d := query.Offset(offset).Limit(limit).Find(&ret.Items).Count(&ret.TotalCount)
	if d.Error != nil {
		return nil, errors.WithCode(code.ErrDatabase, d.Error.Error())
	}
	return &ret, nil
}

var _ v1.UserStore = &users{}
